import React, { useState, useEffect } from 'react';
import BreadCrumb from '@/components/BreadCrumb';
import s from './style.module.css';
// import SelectAnt from '@/components/SelectAnt';
import {
  Table,
  Datetime,
  Button,
  Input,
  Confirm,
  Loading,
  Message,
  Select,
} from '@knownsec/react-component';
import Scanres from './ScanRes';
import TaskAvailability from './taskAvailability';
import InfoBox from './infoBox';
import moment from 'moment';
import { AlleventSole, AlleventGroup, getTimes, putTypeRescan, putRescan, getReport,exportPOST } from '~/API';
import { useLocation, Link, useHistory } from 'react-router-dom';
import { GetQueryString } from '@/common/constant';
import { timeChange, datetime } from '@/common/formatter';

const typeArr = ['CRITICAL', 'HIGH', 'MEDIUM', 'LOW'];
function dashboard() {
  const history = useHistory();
  const [timeOpt, setTimeOpt] = useState([]);
  const [data, setData] = useState();
  const [loading, setLoading] = useState(false);
  const [downlog, setDownlog] = useState(false);
  const search = useLocation().search;
  //target_id
  const id = GetQueryString(search, 'id');
  //task_session_id
  let sid = GetQueryString(search, 'sid');
  const [selVal, setSelVal] = useState(sid);
  const type = GetQueryString(search, 'type');
  const url = GetQueryString(search, 'url');
  const getData = async () => {
    let resSummary = null;
    let times = null;
    if (type !== 'availability') {
      if (type) {
        resSummary = await AlleventGroup(sid);
        times = await getTimes({ id, type });
        console.log('[ times ]-46', times)
        //单个任务时间处理
        if (times.status === 'success') {
          const timeOpt_ = times.data?.task_sessions.map((e) => {
            console.log('[ e ]-47', e)
            const differenceTime = Date.now() - new Date(datetime(e.ended_at)).getTime();
            return {
              label:
                moment(e.ended_at).format('YYYY-MM-DD HH:mm:ss') +
                `（${timeChange(differenceTime)}前）`,
              labelHtml: `<p style="display:flex"><span style="width: 150px;display: inline-block;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;">${datetime(
                e.ended_at
              )}</span>
            <span style="width: 85px;display: inline-block;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;">(${timeChange(
              differenceTime
            )}前)</span></p>`,
              value: e.task_session_id,
            };
          });
          setTimeOpt(timeOpt_);
        }
      } else {
        resSummary = await AlleventSole(id);
      }
      const data = resSummary.data;
      console.log('[  ]-57', data);
      setDataFun(data);
      //统计事件类型数
      setLoading(false);
    }
  };
  const setDataFun = (data) => {
    Object.keys(data.risk_distribution).forEach((key) => {
      if (key != 'score' && Object.keys(data.risk_distribution[key])[0] &&( data.total_url > 0||key==='vul')) {
        data.risk_distribution[key].num = 0;
        Object.values(data.risk_distribution[key]).forEach((v_) => {
          data.risk_distribution[key].num += v_;
        });
      } else {
        data.risk_distribution[key].num = '-';
        typeArr.forEach((e) => {
          data.risk_distribution[key][e] = '-';
        });
      }
    });
    setData(data);
  };
  const immediately = async () => {
    Confirm({
      pro: true,
      title: '提示',
      message: <div className="confirmbox">确认要立即下发吗？</div>,
      onconfirm: async () => {
        let res = null;
        if (type) {
          res = await putTypeRescan({ id, type }).catch((e) => {
            return e;
          });
        } else {
          res = await putRescan({ target_ids: [id] }).catch((e) => {
            return e;
          });
        }
        if (res.status === 'success') {
          Message.show({
            pro: true,
            showClose: false,
            type: 'success',
            message: '下发成功',
          });
        } else {
          let msg = '';
          if (res.message) {
            msg = res.message;
          } else {
            msg = Object.values(res.data)[0];
          }
          Message.show({
            pro: true,
            type: 'error',
            message: msg,
            showClose: false,
          });
        }
      },
      oncancel: () => {},
    });
  };
  const download = async () => {
    setDownlog(true);
    await exportPOST({task_session_id:selVal});
    Confirm({
      title: '提示',
      pro: true,
      className:s.w400p,
      message: <div className="confirmbox">正在导出报告，您可前往报告任务列表获取。</div>,
      onconfirm: () => {
        history.push(`/down`);
      },
      oncancel: () => {},
    });
    setDownlog(false);
  };
  React.useMemo(() => {
    getData();
  }, []);
  return (
    <>
      <BreadCrumb
        arr={[
          { link: '/', name: '监测列表' },
          { link: '', name: '结果详情', active: true },
        ]}
      />
      <div id="sc" className={s.dataMain}>
        <Loading show={loading} />
        <div className={s.head}>
          {type&&type !== 'availability' && (
            <Button
              pro
              className={s.button}
              disabled={downlog}
              onClick={() => {
                download()
              }}
            >
              导出报告
            </Button>
          )}
          {type && type !== 'availability' && (
            <Select
              pro
              value={[selVal]}
              placeholder="检测历史"
              option={timeOpt}
              className={s.sel}
              searchable
              onChange={async ({ selectedItem }) => {
                const e = selectedItem[0].value;
                setSelVal(e);
                const summary = await AlleventGroup(e);
                setDataFun(summary.data);
              }}
            />
          )}
          <Link
            to={{
              pathname: '/form_page',
              search: `id=${id}&type=solo`,
            }}
            className={s.button}
          >
            <Button pro type="primary" className={s.button}>
              <span className={s.linkSpan}>编辑检测任务</span>
            </Button>
          </Link>
          <Button
            pro
            type="primary"
            onClick={() => {
              immediately();
            }}
          >
            立即检测
          </Button>
        </div>
        {type === 'availability' ? (
          <TaskAvailability targetId={id} setLoading={setLoading} url={url} />
        ) : (
          <>
            <div className={s.box1}>{data && <InfoBox data={data} type={type} />}</div>
            <div className={s.tableBox}>
              {data && <Scanres targetId={id} data={data} type={type} sid={selVal} />}
            </div>
          </>
        )}
      </div>
    </>
  );
}
export default dashboard;
